package com.test.down.utils;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.Build;

import androidx.annotation.NonNull;

import java.util.ArrayList;

/**
 * Created by ** on 2018/9/13.
 */
public class PermissionUtil {
    public static final int GET_PERMISSION=0x1001;
    private static VerifyPermissionsCallback callbackMultiple;
    /**
     *
     * @param permissions
     * @return  false 不需要申请权限   true需要申请权限
     */
    public static boolean getPermission(String[] permissions, Activity activity, boolean apply, VerifyPermissionsCallback callback){
        if(permissions==null||permissions.length==0) return false;
        if(apply){
            callbackMultiple=callback;
        }else {
            callbackMultiple=null;
        }
        int pid = Binder.getCallingPid();
        int uid = Binder.getCallingUid();
        ArrayList<String> per=new ArrayList<String>();
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M) {
            for (String permission : permissions) {
                if (activity.checkPermission(permission, pid, uid) != PackageManager.PERMISSION_GRANTED) {
                    per.add(permission);
                }
            }
            if (per.size() > 0) {
                if(apply) {
                    activity.requestPermissions(per.toArray(new String[per.size()]), GET_PERMISSION);
                }
                return true;
            }else {
                return false;
            }
        }else {
            return false;
        }
    }

    ///权限获取的统一处理
    public static void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0 && callbackMultiple != null) {
            ArrayList<String> denyPermissions = new ArrayList<>();
            int i = 0;
            for (String permission : permissions) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    denyPermissions.add(permission);
                }
                i++;
            }
            if (denyPermissions.size() == 0) {
                callbackMultiple.onPermissionAllGranted();
            } else {
                callbackMultiple.onPermissionDeny(denyPermissions.toArray(new String[0]));
            }
        }
    }

    public interface VerifyPermissionsCallback {
        void onPermissionAllGranted();

        void onPermissionDeny(String[] permissions);
    }
}
